//
//  NSString+LCDES.m
//  UI_24_加密
//
//  Created by li cheng on 16/8/16.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "NSString+LCDES.h"
#import <CommonCrypto/CommonCrypto.h>
// 必须八位
#define key @"01234567"
// 向量
static Byte iv[] = {1, 2, 3, 4, 5, 6, 7, 8};
@implementation NSString (LCDES)
// 字符串对称加密(DES)
- (NSString *)stringWithDES{
//    NSString *string = [self description]
    // 1. 将字符串本身转换成C字符串
    const char *string = [self UTF8String];
    unsigned char byte[1024];
    // 容器的大小
    size_t dataOutMoved = 0;
    // 4. 加密额过程
    CCCryptorStatus cryptorStatus =
    // 参数
    // 1. 加密或者解密
    CCCrypt(kCCEncrypt,
            // 2.加密/解密 方式
            kCCAlgorithmDES,
            // 3.分组密码的选项
            kCCOptionPKCS7Padding,
            // 4.密钥
            [key UTF8String],
            // 5. 密钥的大小
            kCCKeySizeDES,
            // 6. 向量
            iv,
            // 7. C 的字符串
            string,
            // 8.长度 length
            strlen(string),
            // 9. 容器
            byte,
            // 10. 容器大小
            1024,
            // 11. 容器的最终个数
            &dataOutMoved);
    // 5. 判断是否成功, 成功了转回base64, 失败返回空.
    if (cryptorStatus == kCCSuccess) {
        NSData *desdata = [NSData dataWithBytes:byte length:dataOutMoved];
        NSString *desBase64String = [desdata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSLog(@"成功");
        return desBase64String;
    } else {
        
        return nil;
    }
}
// 字符串对称解密(DES)
- (NSString *)desWithString{
   NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    const void *byte = base64Data.bytes;
    unsigned char buffer[1024];
    size_t dataOutMoved = 0;
    CCCryptorStatus cryptorStatus =
    CCCrypt(kCCDecrypt,
            kCCAlgorithmDES,
            kCCOptionPKCS7Padding,
            [key UTF8String],
            kCCKeySizeDES,
            iv,
            byte,
            [base64Data length],
            buffer,
            1024,
            &dataOutMoved);
    if (cryptorStatus == kCCSuccess) {
        NSData *sourceData = [NSData dataWithBytes:buffer length:dataOutMoved];
        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
        NSLog(@"解密成功");
        return sourceString;
    }
//    else {
//
        return nil;
//    }
}
@end
